package com.chookss.mine.personal.upload;


import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.chookss.MyApp;
import com.chookss.home.entity.UploadEntity;
import com.chookss.home.gallery.UploadGalleryService;
import com.chookss.home.publish.UploadDocService;
import com.chookss.home.publish.UploadVedioService;
import com.chookss.tools.MyEvent;
import com.chookss.tools.Utils;
import com.chookss.tools.XJson;
import com.johnrambo.ktea.common.klogutil.KLog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class UploadFileService extends Service {
    private List<UploadEntity> list = new ArrayList<>();
    private String resourceType;  //        （1资料，2长视频，3短视频，4新闻，5图文6图片）
    private int index = -1;
    private boolean stopUpload=false;//默认正常上传  当true时切换账号中止上传

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //只走一次
        MyApp.uploadRecordStatus=true;
        EventBus.getDefault().register(this);
        registerBoradcastReceiver();
        KLog.i("jaa","--------onCreate");
    }

    @Override
    public int onStartCommand(final Intent intent, int flags, int startId) {
        //只要存在就直接进来这里
        resourceType = intent.getStringExtra("resourceType");
        KLog.i("jaa","--------onStartCommand" + resourceType + "-");
        if ("1".equals(resourceType)) {
            ArrayList docOldList = intent.getExtras().getParcelableArrayList("data");
            if (docOldList != null) {
                List<UploadEntity> docUploads = (ArrayList<UploadEntity>) docOldList.get(0);
                list.addAll(docUploads);
                XJson.addUploadEntity(this, docUploads, UploadEntity.class);
            }
        } else if ("3".equals(resourceType)) {
            UploadEntity videoBean2 = (UploadEntity) intent.getSerializableExtra("data");
            if (videoBean2 != null) {
                list.add(videoBean2);
                List<UploadEntity> videoUploads = new ArrayList<>();
                videoUploads.add(videoBean2);
                XJson.addUploadEntity(this, videoUploads, UploadEntity.class);
            }
        } else if ("6".equals(resourceType)) {
            UploadEntity picBean2 = (UploadEntity) intent.getSerializableExtra("data");
            if (picBean2 != null) {
                list.add(picBean2);
                List<UploadEntity> picUploads = new ArrayList<>();
                picUploads.add(picBean2);
                XJson.addUploadEntity(this, picUploads, UploadEntity.class);
            }
        }
        KLog.i("jaa","--------onStartCommand" + resourceType + "-" + index + "==" + list.size());
        if (index == -1) {
            //后面进来的都排队，防止一起上传
            KLog.i("jaa","--------onStartCommand第一次");
            setData();
        }

        return super.onStartCommand(intent, flags, startId);
    }

    private void setData() {
        if(stopUpload){
            stopSelf();
            KLog.i("jaa","--------暂停");
            return;
        }
        if(index==-1){
            index=0;
        }
        if (index < list.size()) {
            if ("1".equals(list.get(index).getResourceType())) {
                Intent intent = new Intent(this, UploadDocService.class);
                intent.putExtra("data", list.get(index));
                startService(intent);
                KLog.i("jaa","--------startService");
            } else if ("3".equals(list.get(index).getResourceType())) {
                KLog.i("jaa","--------UploadVedioService");
                Intent intent = new Intent(this, UploadVedioService.class);
                intent.putExtra("data", list.get(index));
                startService(intent);

            } else if ("6".equals(list.get(index).getResourceType())) {
                KLog.i("jaa","=====666666"+System.currentTimeMillis());
                Intent intent = new Intent(this, UploadGalleryService.class);
                intent.putExtra("data", list.get(index));
                startService(intent);
            }
        }
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (context != null && intent != null && intent.getAction() != null) {
                if (action.equals(MyUploadRecordActivity.docTag) || action.equals(MyUploadRecordActivity.picTag) || action.equals(MyUploadRecordActivity.videoTag)) {
                    if (100 == intent.getIntExtra("percent", 100)) {
                        //文件上传完成，进行下一个
                        index++;
                        if (index >= list.size()) {
                            stopSelf();
                        } else {
                            setData();
                        }
                    }
                }
            }
        }

    };
    private boolean registTag = false;//判断重复注册

    private void registerBoradcastReceiver() {
        if (mBroadcastReceiver != null) {
            IntentFilter myIntentFilter = new IntentFilter();
            myIntentFilter.addAction(MyUploadRecordActivity.docTag);// 关闭
            myIntentFilter.addAction(MyUploadRecordActivity.picTag);//销毁service
            myIntentFilter.addAction(MyUploadRecordActivity.videoTag);//销毁service
            //注册广播
            LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, myIntentFilter);
            registTag = true;
        }

    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getMap() != null) {
            Map<String, String> map = messageEvent.getMap();

        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if (msg.equals("Stop_File_Upload")) {
                //中止上传任务
                stopUpload=true;
                MyApp.uploadRecordStatus=false;
                stopSelf();
            }
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        //注销广播
        MyApp.uploadRecordStatus=false;
        KLog.i("jaa","中止文件上传");
        EventBus.getDefault().unregister(this);
        if (mBroadcastReceiver != null && registTag) {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver);
            registTag = false;
        }
    }
}